#include "modules/api.h"
#include "utils/diagnostic.h"
#include "core/gateway.h"

namespace mod {
	DIAGNOSTIC_PUSH
	IGNORE_UNUSED_PARAMETER
	ApiModule::ApiModule(std::shared_ptr<Context> ctx, const string &module_name) : Module(ctx, module_name) {};
	ApiModule::~ApiModule() = default;

	bool ApiModule::Init() { return true; }

	void ApiModule::Start() {
		// Module::Start();
		ctx->eventBus.Subscribe<PingEvent>([](const PingEvent &event) {
			printf("==> [PONG] %d\n", event.SockFd);
			printf("==> [PONG] %s\n", event.SenderIp);
			printf("==> [PONG] %d\n", event.SenderPort);
			printf("==> [PONG] %s\n", event.Result.c_str());
		});
	}

	void ApiModule::Stop() {}

	string ApiModule::Ping() const { return "Pong"; }

	// 获取网关集合(包含本地网关和远程网关)
	void ApiModule::Gateways() const {
		//  GetNatService
		vector<GatewayInfo> result;
		// send(result); //todo
	}

	// 获取服务列表
	void ApiModule::Services() const {
		vector<ServiceInfo>         result;
		unordered_map<int, NatMate> res = ctx->GetNatService();
		// send(result); //todo
	}

	// 获取本地Agent列表
	void ApiModule::Agents() const {
		vector<AgentModel>          result;
		unordered_map<int, NatMate> res = ctx->GetNatService();
		for (const auto &item: res) {
			auto listener = ctx->getListenerByFD(item.first);
			auto now      = timestamp_mills();
			result.push_back(AgentModel{
			        .SockFd   = item.first,
			        .Name     = item.second.Name,
			        .Origin   = netutil::CURRENT_IP4 + ":" + to_string(listener->port),
			        .Gateway  = item.second.GatewayIP + ":" + to_string(item.second.GatewayPort),
			        .Target   = item.second.ServiceIP + ":" + to_string(item.second.ServicePort),
			        .Duration = abs(now - listener->created) / 1000,
			});
		}
		// send(result); //todo
	}

	// 获取本地会话列表
	void ApiModule::Sessions() const {
		vector<SessionModel> result;
		// send(result); //todo
	}
	DIAGNOSTIC_POP
} // namespace mod
